const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const sendThisEmail = require("../public/javascripts/sendyan")//发送验证码
const router = express.Router();
const Writer = require('../models/Writer')
const Book = require("../models/Book");

const Sou = require("../public/javascripts/sousuo")

//注册模块
router.post('/zhuce', (req, res) => {
    //console.log(req.body);
    Writer.findOne({ zhanghao: req.body.zhanghao })
        .then((writer) => {
            if (writer) {
                return res.json({ status:400, msg: '该账号已被注册'})
                //return res.status(400).json({ msg: '该账号已被注册' })
            } else {
                var newWriter = new Writer({
                    zhanghao: req.body.zhanghao,
                    username: req.body.username,
                    password: req.body.password,
                    email: req.body.email,
                })

                bcrypt.genSalt(10, function (err, salt) {
                    bcrypt.hash(newWriter.password, salt, (err, hash) => {
                        if (err) throw err;
                        newWriter.password = hash;
                        newWriter.save()
                            .then(writer => res.json({data:writer,msg:'success'}))
                            .catch(err => console.log(err));
                    });
                });
            }
        });
});


//用户登陆
router.post('/login', (req, res) => {
    //console.log(req.body);
    const id = req.body.id;
    const zhanghao = req.body.zhanghao;
    const password = req.body.password;
    
    Writer.findOne({ zhanghao })
        .then(writer => {
            if (!writer) {
                return res.json({ msg: '账号不存在' })
            }
            //return username;
            bcrypt.compare(password, writer.password)
                .then(isMatch => {
                    if (isMatch) {
                        // jwt.sign("规则"，加密名字，过期时间(s)，箭头函数)
                        const rule = {
                            id: writer.id,
                            zhanghao: writer.zhanghao,
                        }
                        jwt.sign(rule, "theka", { expiresIn: 3600 }, (err, writertoken) => {
                            if (err) throw err;
                            //console.log(writertoken);
                            res.json({
                                id: writer.id,
                                avatar: writer.avatar,
                                username: writer.username,
                                status: 200,
                                state:writer.state,
                                success: true,
                                writertoken: 'Bearer ' + writertoken
                            })
                        })
                    } else {
                        res.json({
                            status: 400,
                            success: false,
                            msg: '用户信息错误'
                        })
                    }
                })
        })
})

//更改头像
router.post("/changeAva/:id", (req, res) => {
    //console.log(req.params.id);
    Writer.findByIdAndUpdate(req.params.id, { $set: { "avatar": req.body.avatar } })
        .then(res.sendStatus(200))
})
//更换名字
router.post("/changeData/:id", (req, res) => {
    
    console.log(req.params.id);
    console.log(req.body.name);
    Writer.findByIdAndUpdate(req.params.id, { $set: { "username": req.body.name } })
        .then(Book.updateMany({ writerid: req.params.id }, { $set: { "writername": req.body.name } }, { multi: true })
            .then(res.sendStatus(200)))
    //Book.updateMany({ writerid: req.params.id }, { $set: { "writername": req.body.name } }, { multi: true })
    //    .then(res.sendStatus(200))
})

//获取二级密码
router.get("/twoPass/:id", (req, res) => {
    console.log(writertoken);
    Writer.findById(req.params.id, { twoPass: 1 })
        .then(twoPass => res.json(twoPass))
})
//设置二级密码
router.post("/setTwoPass/:id", (req, res) => {
    Writer.findByIdAndUpdate(req.params.id, { $set: { "twoPass": req.body.twoPass } })
        .then(a =>res.json({status:200}))
})
//更改密码
router.post("/changPass/:id", (req, res) => {
    let password = req.body.password
    bcrypt.genSalt(10, function (err, salt) {
        bcrypt.hash(password, salt, (err, hash) => {
            if (err) throw err;
            password = hash;
            Writer.findOneAndUpdate(
                { _id: req.params.id },
                { $set: {"password":password} },
                { new: true }
            ).then(user => res.json({status:200}))
        });
    })
})

//更改二级密码
router.post("/changeTwoPass/:id", (req, res) => {
    Writer.findByIdAndUpdate(req.params.id, { $set: { "twoPass": req.body.pass } })
        .then(res.sendStatus(200))
})

//获取邮箱
router.get("/getEmail/:id", ( req, res ) => {
    Writer.findById(req.params.id, { email: 1 })
    .then(email => res.send({data:email,status:200}))
})

//根据账号发送邮箱验证码
router.post("/getEmailByHao", (req, res) => {
    Writer.findOne({ zhanghao: req.body.zhanghao },{email:1})
        .then(hao => {
            if (!hao) {
                return res.json({ status:404,msg: '账号不存在' })
            }
            else {
                let Num = Math.floor((Math.random() * 100000) + 10000);
                const mail = {
                    // 发件人 邮箱  '昵称<发件人邮箱>'
                    from: '爱阅读中文网<2624133733@qq.com>',
                    // 主题
                    subject: '验证码',
                    // 收件人 的邮箱 可以是其他邮箱 不一定是qq邮箱
                    to: hao.email,
                    // 内容
                    text: `您的激活验证码为：${Num}, 本次有效，尽快使用。`,
                    //这里可以添加html标签
                    //html: '<a href="https://www.cnblogs.com/HJ412/">车神-黄杰</a>'
                }
                new sendThisEmail().sendYan(mail)
                res.send({ data: {id:hao._id,Num:Num}, status: 200 })
            }
        }).catch(err => console.log(err))
})

//根据id改变邮箱
router.post("/changeEmail/:id", (req, res) => {
    Writer.findByIdAndUpdate(req.params.id, { $set: { "email": req.body.email } })
        .then(res.sendStatus(200))
})

//根据id获得头像
router.get("/getAva/:id", (req, res) => {
    Writer.findById(req.params.id, { avatar: 1 })
        .then(ava => res.send({data:ava,status:200}))
})

//根据id获取名字和头像
router.get("/getAN/:id", (req, res) => {
    Writer.findById(req.params.id, { avatar: 1,username:1 })
    .then(ava => res.send({ data: ava, status: 200 }))
})

router.get("/ceshi/:id", (req, res) => {
    Writer.findById(req.params.id, { username: 1, date: 1, state: 1, email: 1 })
        .then(w => res.send({data:w,status:200}))
})

// 封禁解封作者
router.post("/updateWriterState/:id", (req, res) => {
    Writer.findByIdAndUpdate(req.params.id, { $set: { "state": req.body.state } })
        .then(res.send({ status: 200 }))
})

//获取所有作者
router.post("/allWriter", (req, res) => {
    let a = req.body.pageSize;
    let b = req.body.currentPage
    let c = (b - 1) * a;
    Writer.find({}, {
        username:1,email:1,state:1,date:1
    }).skip(c).limit(a)
        .then(w => {
            Writer.find().countDocuments(true)
                .then(num => res.send({data:w,num:num,status:200}))
    })
})

//删除作者
router.delete("/deleteThisWriter/:id", (req, res) => {
    Writer.findByIdAndDelete(req.params.id)
        .then(res.sendStatus(200))
})
module.exports = router